import { AfterViewInit, Component, ElementRef, OnInit, ViewChild } from '@angular/core'

@Component({
  selector: 'app-ex0304',
  templateUrl: './ex0304.component.html',
  styleUrls: ['./ex0304.component.scss']
})
export class Ex0304Component implements OnInit, AfterViewInit {
  private cnv: any
  private ctx: any

  @ViewChild('canvas')
  set canvas(ref: ElementRef) {
    this.cnv = ref.nativeElement
    this.ctx = ref.nativeElement.getContext('2d')
  }

  constructor() {
  }

  ngOnInit(): void {
  }

  ngAfterViewInit(): void {
    // this.draw1(this.ctx)
    // this.draw2(this.ctx)
    this.draw3(this.ctx)
  }

  draw1(ctx): void {
    ctx.moveTo(20, 80)
    const cx1 = 20
    const cy1 = 20
    const cx2 = 120
    const cy2 = 120
    const endX = 120
    const endY = 60
    ctx.bezierCurveTo(cx1, cy1, cx2, cy2, endX, endY)
    ctx.stroke()
  }

  draw2(ctx): void {
    ctx.moveTo(75, 40)
    ctx.bezierCurveTo(75, 37, 70, 25, 50, 25)
    ctx.bezierCurveTo(20, 25, 20, 62.5, 20, 62.5)
    ctx.bezierCurveTo(20, 80, 40, 102, 75, 120)
    ctx.bezierCurveTo(110, 102, 130, 80, 130, 62.5)
    ctx.bezierCurveTo(130, 62.5, 130, 25, 100, 25)
    ctx.bezierCurveTo(85, 25, 75, 37, 75, 40)

    ctx.stroke()
  }

  draw3(ctx): void {
    this.createLeaf(ctx, 4, this.cnv.width / 2, this.cnv.height / 2, 20, 80)
    ctx.fillStyle = '#00FF99'
    ctx.fill()
  }

  createLeaf(ctx, n, dx, dy, size, length): void {
    ctx.beginPath()
    ctx.moveTo(dx, dy + size)

    const degree = 2 * Math.PI / n
    for (let i = 0; i < n + 1; i++) {
      const cx1 = Math.sin((i - 1) * degree) * length + dx
      const cy1 = Math.cos((i - 1) * degree) * length + dy
      const cx2 = Math.sin(i * degree) * length + dx
      const cy2 = Math.cos(i * degree) * length + dy
      const x = Math.sin(i * degree) * size + dx
      const y = Math.cos(i * degree) * size + dy
      ctx.bezierCurveTo(cx1, cy1, cx2, cy2, x, y)
    }

    ctx.closePath()
  }
}
